<template>
	<view>
		<form :model="form">

			<view class="uni-form-item uni-column">
				<view class="title">姓名</view>
				<input class="uni-input" name="input" v-model="form.name" placeholder="请输入姓名" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">年龄</view>
				<input class="uni-input" name="input" v-model="form.age" placeholder="请输入年龄" />
			</view>

			<view class="uni-btn-v">
				<button @click="submit">提交</button>
			</view>
		</form>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					"id": null,
					"name": null,
					'age': null
				}
			}
		},
		onLoad(e) {
			// console.log(e)
			if (e.id) {
				console.log('update')
				this.loadData(e.id)
			} else {
				console.log('add')
			}
		},
		methods: {
			//加载数据
			loadData(id) {
				let that = this
				uni.request({
					url: `http://localhost:9000/uniapp/student/${id}`,
					method: 'GET',
					success: (res) => {
						that.form = res.data
					},
					fail: (err) => {
						console.error(err)
					}
				});
			},
			//表单提交
			submit() {
				let that = this
				if(this.form.id){
					uni.request({
						url: `http://localhost:9000/uniapp/student`,
						method: 'PUT',
						data: that.form,
						success: (res) => {
							if(res.data.id){
								uni.navigateTo({
									url: `/pages/index/index`
								})
							}
						},
						fail: (err) => {
							console.error(err)
						}
					});
				}else{
					uni.request({
						url: `http://localhost:9000/uniapp/student`,
						method: 'POST',
						data: that.form,
						success: (res) => {
							if(res.data.id){
								uni.navigateTo({
									url: `/pages/index/index`
								})
							}
						},
						fail: (err) => {
							console.error(err)
						}
					});
				}
				
			}
		}
	}
</script>

<style>

</style>
